/* eslint-disable @typescript-eslint/no-unused-vars */
import { getUserForgetPwd, postTeacherLogin, poststudentLogin, postUserRegesiter, postUserResetPwd } from '@/services/cms/14383';
import { setToken } from '@/utils/auth';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message, Radio } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import React, { useState } from 'react';
import RegisterForm from './components/RegisterForm';
import type { RegisterFormDetail } from './components/types';
import { registerType } from './constants';
import { history, useModel } from 'umi';
import styles from './style.less';
import ForgetPwdForm from './components/ForgetPwdForm';
import ChangePwdForm from './components/ChangePwdForm';

import { SmileOutlined } from '@ant-design/icons';

const { Item } = Form;
const LoginPage: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [forgetModalVisible, setForgetModalVisible] = useState<boolean>(false);
  const [changeModalVisible, setChangeModalVisible] = useState<boolean>(false);

  const [value, setValue] = useState();
  const [tempToken, setTempToken] = useState()

  const [form] = useForm();

  const { initialState, setInitialState } = useModel('@@initialState');

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();

    if (userInfo) {
      setInitialState({
        ...initialState,
        currentUser: userInfo,
      });
    }
  };

  // 登录前往范本页面或者是默认页面
  const goto = () => {
    if (!history) return;
    setTimeout(() => {
      const { query } = history.location;
      const { redirect } = query as { redirect: string };
      history.push(redirect || '/');
    }, 10);
  };

  // 通过用户信息进行登录
  const loginDone = async (values: RegisterFormDetail) => {
    // const res = await postUserLogin(values);
    // if (res.code === '0') {setToken
    //   (res.data as string);
    //   await fetchUserInfo();
    //   goto();
    // }
    let res;
    const loginValues = { email: values.email, password: values.password }
    if (values.type === 1) {
      res = await postTeacherLogin(loginValues)
      localStorage.setItem('user', res?.data?.teacher?.teacherName)
      localStorage.setItem('info', JSON.stringify(res?.data?.teacher))
    } else {
      res = await poststudentLogin(loginValues)
      localStorage.setItem('user', res?.data?.student?.studentName)
      localStorage.setItem('info', JSON.stringify(res?.data?.student))
    }
    if (res.code === 200) {
      location.reload();
      localStorage.setItem('userType', value || '')
      setToken(res.data.token as string);
      goto();
      await fetchUserInfo();
    } else {
      message.error('账号或密码错误！')
    }
  };

  // 处理登录按钮响应
  const handleLogin = async () => {
    const { validateFields } = form;
    const content = await validateFields();
    await loginDone(content);
  };

  // 处理注册弹窗确定按钮
  const handleRegister = async (values: RegisterFormDetail) => {
    const res = await postUserRegesiter({ registerSrc: registerType.regisiter, ...values });
    if (res.code === '0') {
      message.success('注册成功');
      setCreateModalVisible(false);
      // 注册完自动帮用户登录
      loginDone(values);
    }
  };

  // 相应注册按钮
  // const handleRegisterBtn = () => {
  //   setCreateModalVisible(true);
  // };

  // 忘记密码弹窗确定响应
  const handleForgetPwd = async (values: RegisterFormDetail) => {
    const res = await getUserForgetPwd({ ...values });
    // setTempToken(res?.data?.verification-token)
    if (res.code === 200) {
      message.success('发送邮件成功，请在收到邮件后复制验证码进行修改密码');
      setForgetModalVisible(false);
      setChangeModalVisible(true)
      setTempToken(res?.data['verification-token'])
    }
  };

  // 修改密码窗口响应
  const handleChangePwd = async (values: RegisterFormDetail) => {
    const changeValue = { ...values, token: tempToken }
    const res = await postUserResetPwd({ ...changeValue });
    if (res.code === 200) {
      message.success('修改成功');
      setChangeModalVisible(false);
    }
  };

  // 响应忘记密码按钮
  const handleForgetPwdBtn = () => {
    setForgetModalVisible(true);
  };

  // 判断登陆类型
  const onChange = (e: any) => {
    setValue(e.target.value);
  };



  const code = localStorage.getItem('code')
  if (code !== 'pass') {
    return (
      <div className={styles.loginWarp}>
        <Form form={form}>
          <div className={styles.loginMain}>
            <h3 className={styles.title}><img src={require('../../images/logo.svg')} className={styles.icon} />JAVA判题系统</h3>
            <Item name="email" rules={[{ required: true }]} label="邮箱">
              <Input size="large" placeholder="请输入邮箱" prefix={<UserOutlined />} />
            </Item>
            <Item name="password" rules={[{ required: true }]} label="密码">
              <Input
                size="large"
                type="password"
                placeholder="请输入密码"
                onPressEnter={handleLogin}
                prefix={<LockOutlined />}
              />
            </Item>
            <Item name="type" rules={[{ required: true }]} label="类型">
              <Radio.Group onChange={onChange} value={value} >
                <Radio value={1}>教师</Radio>
                <Radio value={2}>学生</Radio>
              </Radio.Group>
            </Item>
            <Button className={styles.signInBtn} type="primary" onClick={handleLogin}>
              登录
          </Button>
            <div className={styles.tool}>
              {/* <Button className={styles.button} onClick={handleRegisterBtn}>
                注册
            </Button> */}
              <Button className={styles.button} type="link" onClick={handleForgetPwdBtn}>
                忘记密码
            </Button>
            </div>
          </div>
        </Form>
        <RegisterForm
          onCancel={() => {
            setCreateModalVisible(false);
          }}
          onSubmit={handleRegister}
          createModalVisible={createModalVisible}
        />
        <ForgetPwdForm
          onCancel={() => {
            setForgetModalVisible(false);
          }}
          onSubmit={handleForgetPwd}
          createModalVisible={forgetModalVisible}
        />
        <ChangePwdForm
          onCancel={() => {
            setChangeModalVisible(false)
          }}
          onSubmit={handleChangePwd}
          createModalVisible={changeModalVisible}
        />
        {/* <div className={styles.loginMain}>
          <h3 className={styles.title}>自制资产管理平台</h3>
          <Result
            icon={<SmileOutlined />}
            subTitle="您暂无权限操作，请联系limingzheng添加权限"
            extra={
              <Button type="primary" onClick={() => {
                if (code !== 'pass') {
                  window.alert('您暂无权限操作，请联系limingzheng添加权限')
                } else {
                  history.push('/');
                }
              }}>
                Back Home
              </Button>
            }
          />
        </div> */}
      </div>
    );
  } else {
    history.push('/');
  }
  return <></>
};

export default LoginPage;
